package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {


    @Override
    public ResponseResult findByName(String name) {

        LambdaQueryWrapper<WmUser> query = Wrappers.<WmUser>lambdaQuery();

        query.eq(WmUser::getName,name);

        WmUser wmUser = this.getOne(query);

        return ResponseResult.okResult(wmUser);
    }

    @Override
    public ResponseResult login(WmUserDTO dto) {
        //1.校验参数

        String name = dto.getName();
        String password = dto.getPassword();

        if (name ==null|| password ==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空");
        }

        //2.判断用户名是否存在

        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, name));

        if (wmUser==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不存在");
        }

        //3.判断用户状态是否可用

        if (wmUser.getStatus()!=9) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常");
        }

        //4.判断密码是否正确

        String salt = wmUser.getSalt();//获取盐

        String pw = DigestUtils.md5DigestAsHex((password + salt).getBytes());//spring框架的DigestUtils类的md5加密方法得到密文

        if (!wmUser.getPassword().equals(pw)) {//与数据库中的密文比较
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }


        //5.设置登录时间

        Date date = new Date();

        wmUser.setLoginTime(date);

        this.updateById(wmUser);

        //6.登陆成功，生成token

        String token = AppJwtUtil.getToken(wmUser.getId().longValue());

        //7.封装返回响应数据

        WmUserVO wmUserVO = new WmUserVO();

        BeanUtils.copyProperties(wmUser,wmUserVO);//spring框架自带的工具类，对象属性拷贝

        HashMap<String, Object> map = new HashMap<>();

        map.put("token",token);
        map.put("user",wmUserVO);//

        return ResponseResult.okResult(map);

    }
}
